
/**
 * Created by wangjiakun on 2018/6/20 0020.
 */
import React from 'react';

import { messages, getApprovelHistory, queryCurrencyPrecision, currencyPrecisionCal } from 'share/common';
import { connect } from 'react-redux';
import {Form, Row, Col, Input, Spin, Select, Button, Switch, InputNumber, Alert, Modal, Checkbox, TimePicker, message, Affix, Popconfirm,Icon} from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
import SubsidyRuleService from 'containers/expense-reimbursement-control/expense-standard/subsidy-rule/subsidy-rule-service';
import 'styles/expense-reimbursement-control/expense-standard/subsidy-rule/subsidy-rule.scss';
import 'styles/request/travel-request/travel-type.scss';
import chooserData from 'share/chooserData';
import CalculateForm from 'containers/expense-reimbursement-control/expense-standard/subsidy-rule/calculate-form';
import 'styles/custom-fields.scss'
import Chooser from 'components/chooser'
import moment from 'moment';
import ruleUtil from 'containers/expense-reimbursement-control/expense-standard/subsidy-rule/subsidy-rule-util';
import config from "config";

class NewSubsidyRules extends React.Component{
  returnOperator = 1001;//操作符 *
  returnIsUseStandard = true;//是否使用标准
  returnOperatorDivisor = 1;//返回当天操作因子
  returnAmount = 0;//返回当天金额
  departureOperator = 1001;//操作符 *
  departureIsUseStandard = true;//是否使用标准
  departureOperatorDivisor = 1;//出差当天操作因子
  departureAmount = 0;//出差当天金额
  statRuleItem = "";//暂时存放要添加的规则
  currentAddIsDeparture = false;//添加的规则是否是出差当天的
  currentIndex = -1;//当前编辑的规则下标
  amountLessThanZero = false;
  ruleNameRepeat = false;//规则名称是否重复
  isCanSave = true;//是否可以提交保存
  arr = [];//对应state里面的fieldValueData
  statusIsEdit = false;//当前侧滑的状态，默认false->新建状态,true-->编辑状态
  constructor(props){
    super(props);
    this.state = {
      unInstallWeek:false,//卸载周末差补控件
      isRequest:false,//后台交互
      isOk:false,//确定
      isOkAndCopy:false,//确定并复制
      isAddNewRule:false,//新建规则弹框控制量
      weekendAmount:0,
      currentCodeShow:'',//当前要展示的币种
      citys:[],//差补城市
      fieldValueData:[],//自定义列表选择值
      itineraryValueData: {},//行程值列表选择值
      currentCode:[],//币种
      formInfo:{},//表单数据
      departureConditions:[],//出差当天规则
      returnConditions:[],//返回当天的规则
      travelSubsidiesConditions:[],//
      departure:{amount:0},//出差当天
      backReturn:{amount:0},//返回当天
      isEditModal:false,//是否是编辑状态的modal， false为新建状态，true为编辑
      isDeparture:false,//是否是编辑或者新增的出差当天规则，否则为返回当天
      isShowDefaultTip:false,//是否显示默认规则的提示-->“当未能匹配其他规则时，系统将引用该金额”
      editRuleItem:{},//承载被编辑的规则项（包含返回当天，出差当天）
      editRuleDetailItem:{},//承载被编辑的规则的详情（已添加过的规则进行编辑时拿到的相关详情数据）
      chooserItem:{},//适用人员控件参数
    }
  }

  componentDidMount(){
    this.initData(true,true,true);
    let chooserItem = chooserData['user_group'];
    // chooserItem.url = chooserItem.url + '?enabled=true';
    this.setState({chooserItem:chooserItem});
  }

  componentWillReceiveProps(nextProps){
    if(nextProps.params.isUpdate){
      this.props.params.callBack(false,false,false);
      this.initData(false,false,true);
    }
    if(nextProps.params.isEditRule && !this.statusIsEdit){
      this.statusIsEdit = true;
      this.setState({unInstallWeek:true,isRequest:true});
      this.props.params.callBack(false,false,true);
      SubsidyRuleService.getRuleDetail(nextProps.params.btnItem.id).then(res =>{
        let returnConditions = res.data.returnConditions ? res.data.returnConditions : [];
        let departureConditions = res.data.departureConditions ? res.data.departureConditions : [];
        this.updateSetDefault(res.data);
        this.setState({
          isRequest:false,
          editRuleDetailItem:res.data,
          returnConditions:returnConditions,
          departure:{amount:res.data.departureAmount ? res.data.departureAmount : 0},
          backReturn:{amount:res.data.returnAmount ? res.data.returnAmount : 0},
          departureConditions:departureConditions
        },()=>{
          this.setState({unInstallWeek:false,isRequest:false});
          if(this.props.params.isCopyRule){
            this.isRepeatName(this.state.editRuleDetailItem.name);
          }
          this.props.form.resetFields();
        })
      }).catch(err =>{
        message.error(err.response.data.message);
      })
    }
  };

  //初始化数据(城市，币种，表单设置)
  initData = (city, code, form) => {
    const { itineraryValueData } = this.state;
    if(city){
      SubsidyRuleService.getSubsidyCityData().then(res =>{
        let cityArr = [];
        for(let i=0;i<res.data.length;i++){
          if(!res.data[i].deleted){
            cityArr.push(res.data[i]);
          }
        }
        this.setState({citys:cityArr});
      }).catch(err =>{
        message.error(err.response.data.message);
      });
    }
    if(code){
      let lan = this.props.language.code === 'zh_cn' ? 'zh_cn' : 'en';
      SubsidyRuleService.getCurrentCodeData(this.props.company.baseCurrency, lan, this.props.company.setOfBooksId, this.props.company.tenantId).then(res =>{
        this.setState({currentCode:res.data,currentCodeShow:res.data.rows[0].currencyCode},()=>{
          this.props.form.resetFields();
        });
      }).catch(err =>{
        message.error(err.response.data.message);
      });
    }
    if(form){
      SubsidyRuleService.getSubsidyFormData(this.props.params.formOID).then(res =>{
        this.setState({formInfo: res.data, itineraryValueData: {}}, () => {
          const { formInfo } = this.state;
          //处理表单值列表
          if (formInfo.formFields) {
            //先进行置空
            this.arr = [];
            formInfo.formFields.map((item, num) => {
              SubsidyRuleService.getFieldValues(JSON.parse(item.dataSource).customEnumerationOID).then(res =>{
                let index = this.getIndex(JSON.parse(item.dataSource).customEnumerationOID);
                if (index > -1) {
                  this.arr[index] = res.data.values;
                }
                if (this.arr.filter(obj => obj).length === formInfo.formFields.length) {
                  this.setState({fieldValueData: this.arr});
                }
              });
            });
          }
          //处理行程值列表
          if (formInfo.itineraryFieldOIDs) {
            formInfo.itineraryFieldOIDs.map(customEnumerationOID => {
              SubsidyRuleService.getFieldValues(customEnumerationOID).then(res =>{
                itineraryValueData[customEnumerationOID] = res.data.values;
                this.setState({itineraryValueData});
              });
            });
          }
        });
      }).catch(err =>{
        message.error(err.response.data.message);
      });
    }
  };

  //值列表在formInfo.formFields中的顺序
  getIndex = (customEnumerationOID) => {
    let index = -1;
    this.state.formInfo.formFields && this.state.formInfo.formFields.map((item, fieldIndex) => {
      if (JSON.parse(item.dataSource).customEnumerationOID === customEnumerationOID) {
        index = fieldIndex;
      }
    });
    return index;
  };

  //值列表在formInfo.formFields中的第fieldIndex个的customEnumerationOID
  getCustomEnumerationOID = (fieldIndex) => {
    let customEnumerationOID = '';
    this.state.formInfo.formFields && this.state.formInfo.formFields.map((item, index) => {
      if (fieldIndex === index) {
        customEnumerationOID = JSON.parse(item.dataSource).customEnumerationOID;
      }
    });
    return customEnumerationOID;
  };

  //设置编辑状态的出差当天和返回的默认值
  updateSetDefault = (data) =>{
    this.departureIsUseStandard = data.departureReferenceStandard;//是否引用不标准
    this.departureOperator = data.departureOperator;//操作符
    this.departureOperatorDivisor = data.departureOperatorDivisor;//因数
    this.departureAmount = data.departureAmount ? data.departureAmount : 0;//金额最终值

    this.returnAmount = data.returnAmount ? data.returnAmount : 0;
    this.returnOperator = data.returnOperator;//操作符 *
    this.returnIsUseStandard = data.returnReferenceStandard;//是否使用标准
    this.returnOperatorDivisor = data.returnOperatorDivisor;//返回当天操作因子
  };

  //保存所有规则 type submit/copy
  toSubmitNewRule = (type) =>{
    if(this.amountLessThanZero){
      message.error(messages('setting.key1116'/*差补金额不能小于0*/));
      return;
    }
    if(this.ruleNameRepeat){
      message.error(messages('setting.key1117'/*规则名重复*/));
      return;
    }
    const {tenantMode,company} = this.props;
    this.props.form.validateFieldsAndScroll((err,values) => {
      if(values.ori_user_restriction === 1007 && !values.ori_user.length) {
        message.error(`${messages('common.please.select'/*请选择*/)}${messages('setting.key1092'/*适用人员*/)}`);
        return;
      }
      if(values.ori_city_restriction === 1007 && !values.ori_city.length) {
        message.error(`${messages('common.please.select'/*请选择*/)}${messages('setting.key1093'/*差补城市*/)}`);
        return;
      }
      if(!err){
        let userOID = '';
        values.ori_user.map(u=>{
          userOID = userOID + u.userGroupOID + ',';
        });
        userOID = userOID ? userOID.substring(0,userOID.length - 1) : '';
        let params = {
          formOID:this.props.params.formOID,
          enabled:values.enabled,
          name:values.name,
          expenseTypeOID:this.props.params.isCopyRule ? this.props.params.copyTarget.expenseTypeOID : this.props.params.btnItem.expenseTypeOID,
          expenseTypeName:this.props.params.isCopyRule ? this.props.params.copyTarget.expenseTypeName : this.props.params.btnItem.expenseTypeName,
          currencyCode:values.currencyCode ? values.currencyCode : this.props.company.baseCurrency,
          standardAmount:values.standardAmount,
          travelSubsidiesConditions:[
            {
              messageKey: "USER_GROUPS",
              fieldType: 101,
              restriction: values.ori_user_restriction,
              values: userOID
            },
            {
              messageKey: "ALLOWANCE_CITY",
              fieldType: 101,
              restriction: values.ori_city_restriction ? values.ori_city_restriction : 1006,
              values: values.ori_city ? values.ori_city.join(',') : ''
            }
          ]
        }
        this.setOtherParams(params, values);
        if(this.isCanSave){
          this.setState({isOk:type === 'commit',isOkAndCopy:type === 'copy'});
          if(this.statusIsEdit){
            let editItem = this.state.editRuleDetailItem;
            if(!this.props.params.isCopyRule){//不是复制
              params = Object.assign(editItem,params);
              SubsidyRuleService.updateRule(params,tenantMode?this.props.params.setOfBooksId:'').then(res =>{
                if(type === 'commit'){
                  this.props.callBack(false,true);
                }else{
                  this.props.callBack(false,true,false,params);
                }
                this.statusIsEdit = false;
                this.closeSlide(true);
              }).catch(err =>{
                message.error(err.response.data.message);
                this.setState({isOk:false,isOkAndCopy:false});
              })
            }else if(this.props.params.isCopyRule){//复制
              SubsidyRuleService.saveRule(params,tenantMode?this.props.params.setOfBooksId:'').then(res =>{
                if(type === 'commit'){
                  this.props.callBack(false,true);
                }else{
                  this.props.callBack(false,true,false,params);
                }
                this.closeSlide(true);
              }).catch(err => {
                message.error(err.response.data.message);
                this.setState({isOk:false,isOkAndCopy:false});
              })
            }
          }else{
            SubsidyRuleService.saveRule(params,tenantMode?this.props.params.setOfBooksId:'').then(res =>{
              if(type === 'commit'){
                this.props.callBack(false,true);
              }else{
                this.props.callBack(false,true,false,params);
              }
              this.closeSlide(true);
            }).catch(err => {
              message.error(err.response.data.message);
              this.setState({isOk:false,isOkAndCopy:false});
            })
          }

        }else{
          this.isCanSave = true;
        }
      }
    });
  };

  //根据配置设置所需参数
  setOtherParams = (params, values) => {
    const { formInfo } = this.state;
    if(formInfo.travelFieldDimension){
      if(formInfo.travelFieldDimension.indexOf('TRAVEL_HOURS') >= 0){
        this.setHourseParams(params, values);
      }
      if(formInfo.travelFieldDimension.indexOf('TRAVEL_DAYS') >= 0){
        this.setDaysParams(params, values);
      }
    }
    if(formInfo.specialDimension){
      if(formInfo.specialDimension.indexOf('HOLIDAY_WEEKEND') >= 0){
        this.setWeekendParams(params, values);
      }
      if(formInfo.specialDimension.indexOf('DEPARTURE_DAY') >= 0){
        this.setDepartureParams(params, values);
      }
      if(formInfo.specialDimension.indexOf('RETURN_DAY') >= 0){
        this.setReturnParams(params, values);
      }
    }
    if(formInfo.formFieldOIDs && formInfo.formFieldOIDs.length > 0){//自定义
      let fieldOIDs = formInfo.formFieldOIDs;
      let field = formInfo.formFields;
      if (field) {
        for(let i=0;i<field.length;i++){
          let item = {
            messageKey:"CUST_LIST",
            fieldCode:fieldOIDs[i],
            values:values['field'+i] ? values['field'+i].join(',') : '',
            restriction:values['range'+i]
          }
          params.travelSubsidiesConditions.push(item);
        }
      }
    }
    //处理行程值列表
    if (formInfo.itineraryFieldOIDs && formInfo.itineraryFieldOIDs.length) {
      formInfo.itineraryFieldOIDs.map(itineraryFieldOID => {
        let item = {
          messageKey: "ITINERARY_CUST_LIST",
          fieldCode: itineraryFieldOID, //这个就是customEnumerationOID
          values: values['field' + itineraryFieldOID] ? values['field' + itineraryFieldOID].join(',') : '',
          restriction:values['range' + itineraryFieldOID]
        };
        params.travelSubsidiesConditions.push(item);
      });
    }
  };

  //出差时长
  setHourseParams = (params, values) =>{
    let hourItem = {
      messageKey:"TRAVEL_HOURS",
      fieldType:101,
      restriction:1000,
      values:""
    }
    if(values.hour2 === 0 && values.hour3 !== 1002){
      this.isCanSave = false;
      message.error(messages('setting.key1118'/*出差时长需大于0*/));
    }
    if(values.hour5 === 0){
      this.isCanSave = false;
      message.error(messages('setting.key1119'/*出差时长区间不对*/));
    }
    if(values.hour2 || values.hour2 === 0){
      if(values.hour5){
        hourItem.restriction = 1008;
        hourItem.values = `${values.hour3 === 1002 ? '(' : '['}${values.hour2},${values.hour5}${values.hour4 === 1004 ? ')' : ']'}`;
        if(values.hour4 === 1004){//小于
          if(values.hour2 >= values.hour5){
            this.isCanSave = false;
            message.error(messages('setting.key1119'/*出差时长区间不对*/));
          }
        }else{//小于等于
          if(values.hour2 > values.hour5){
            this.isCanSave = false;
            message.error(messages('setting.key1119'/*出差时长区间不对*/));
          }
        }
        if(values.hour3 === 1002 && this.isCanSave){//大于
          if(values.hour2 === values.hour5){
            this.isCanSave = false;
            message.error(messages('setting.key1119'/*出差时长区间不对*/));
          }
        }
      }else{
        hourItem.restriction = values.hour3;
        hourItem.values = values.hour2;
      }
    }else if(values.hour5){
      hourItem.restriction = values.hour4;
      hourItem.values = values.hour5;
    }
    params.travelSubsidiesConditions.push(hourItem);
  };

  //出差天数
  setDaysParams = (params, values) =>{
    let dayItem = {
      messageKey:"TRAVEL_DAYS",
      fieldType:101,
      restriction:1000,
      values:""
    }
    if((values.day2 === 0 && values.day3 !== 1002)){
      this.isCanSave = false;
      message.error(messages('setting.key1120'/*出差天数需大于0*/));
    }
    if(values.day5 === 0){
      this.isCanSave = false;
      message.error(messages('setting.key1121'/*出差天数区间不对*/));
    }
    if(values.day2 || values.day2 === 0){
      if(values.day5){
        dayItem.restriction = 1008;
        dayItem.values = `${values.day3 === 1002 ? '(' : '['}${values.day2},${values.day5}${values.day4 === 1004 ? ')' : ']'}`;
        if(values.day4 === 1004){
          if(values.day2 >= values.day5){
            this.isCanSave = false;
            message.error(messages('setting.key1121'/*出差天数区间不对*/));
          }
        }else{
          if(values.day2 > values.day5){
            this.isCanSave = false;
            message.error(messages('setting.key1121'/*出差天数区间不对*/));
          }
        }
        if(values.day3 === 1002 && this.isCanSave){//大于
          if(values.day2 === values.day5){
            this.isCanSave = false;
            message.error(messages('setting.key1121'/*出差天数区间不对*/));
          }
        }
      }else{
        dayItem.restriction = values.day3;
        dayItem.values = values.day2;
      }
    }else if(values.day5){
      dayItem.restriction = values.day4;
      dayItem.values = values.day5;
    }
    params.travelSubsidiesConditions.push(dayItem);
  };

  //周末差补
  setWeekendParams = (params, values) =>{
    params.weekendReferenceStandard = values.weekend.isUseStandard;
    params.weekendOperator = values.weekend.restriction;
    params.weekendOperatorDivisor = values.weekend.divisor;
    params.weekendAmount = values.weekend.amount;
  };

  //返回当天
  setReturnParams = (params, values) =>{
    params.returnStandardAmount = values.standardAmount;//返回当天标准金额
    // params.returnStandAmount = values.standardAmount;//*已过期*/
    params.returnReferenceStandard = this.returnIsUseStandard;//是否引用标准金额
    params.returnOperator = this.returnOperator;//操作符 *
    params.returnOperatorDivisor = this.returnOperatorDivisor;//返回当天操作因子
    params.returnAmount = this.returnAmount >= 0 ? this.returnAmount : values.standardAmount;//返回当天金额
    params.returnConditions = this.state.returnConditions.length > 0 ? this.state.returnConditions : [];
  };

  //出差当天
  setDepartureParams = (params, values) =>{
    params.departureStandardAmount = values.standardAmount;//出差当天标准金额
    // params.departureStandAmount = values.standardAmount;//*已过期*/
    params.departureReferenceStandard = this.departureIsUseStandard;//是否引用标准金额
    params.departureOperator = this.departureOperator;//操作符 *
    params.departureOperatorDivisor = this.departureOperatorDivisor;//出差当天操作因子
    params.departureAmount = this.departureAmount >= 0 ? this.departureAmount : values.standardAmount;//出差当天金额
    params.departureConditions = this.state.departureConditions.length > 0 ? this.state.departureConditions : [];
  };

  //保存单个规则
  toSaveSingleRule = () =>{
    let isSetDay = this.props.form.getFieldValue('workDay');
    let isSetWeek = this.props.form.getFieldValue('workWeek');
    let start = this.props.form.getFieldValue('startTime');
    let end = this.props.form.getFieldValue('endTime');
    if(!isSetDay && !isSetWeek){
      message.error(messages('setting.key1122'/*请选择出差时间*/));
      return;
    }
    if(!start || !end || start > end){
      message.error(messages('setting.key1123'/*时间区间不对*/));
      return;
    }
    let subsidy = {};
    let isCancel = true;
    let currentType = ''
    this.props.form.validateFieldsAndScroll((err,values) => {
      if(this.state.isShowDefaultTip){
        if(this.state.isDeparture){
          currentType = 'default_departure'
          subsidy = values.departureDefault;
        }else{
          currentType = 'default_return'
          subsidy = values.returnDefault;
        }
      }else{
        currentType = 'normal';
        subsidy = values.normalSubsidy;
      }
      if(!subsidy.isUseStandard){
        subsidy.restriction = 1001;
        subsidy.divisor = 1;
      }
      if(subsidy.amount < 0 || subsidy.amount === undefined){
        isCancel = false;
        message.error(messages('setting.key1124'/*请检查差补金额*/));
        return;
      }
      if(!subsidy.divisor && subsidy.divisor !== 0){
        isCancel = false;
        message.error(messages('setting.key1124'/*请检查差补金额*/));
        return;
      }
      if(this.state.isEditModal){//编辑
        if(currentType === 'normal'){//非默认规则
          this.addCommitItem(values,null,subsidy);
        }else if(currentType === 'default_departure'){//出差当天默认
          this.departureAmount = subsidy.amount;
          this.departureIsUseStandard = subsidy.isUseStandard;
          this.departureOperator = subsidy.restriction;
          this.departureOperatorDivisor = subsidy.divisor;
          this.setState({departure:{amount:subsidy.amount}},()=>{
            this.standardAmountChange(this.props.form.getFieldValue('standardAmount'));
          });
        }else if(currentType === 'default_return'){//返回当天默认
          this.returnAmount = subsidy.amount;
          this.returnIsUseStandard = subsidy.isUseStandard;
          this.returnOperator = subsidy.restriction;
          this.returnOperatorDivisor = subsidy.divisor;
          this.setState({backReturn:{amount:subsidy.amount}},()=>{
            this.standardAmountChange(this.props.form.getFieldValue('standardAmount'));
          });
        }
      }else{
        this.setState({isRequest:true});
        SubsidyRuleService.getBatchCode().then(res => {
          this.addCommitItem(values, res, subsidy);
        }).catch(err =>{
          this.setState({isRequest:false});
          message.error(err.response.data.message);
        });
      }
    });
    if(isCancel){
      this.cancelAddRule(true);
    }
  }

  //构造一个单个规则（出差当天，返回当天的单项规则）
  addCommitItem = (values, res, subsidy) =>{
    let day = values.workDay ? 1001 : '';
    let week = values.workWeek ? 1003 : '';
    let startTime = values.startTime.format('HH:mm');
    let endTime = values.endTime.format('HH:mm');
    let isSplice = false;
    if(this.state.isEditModal && this.currentAddIsDeparture){
      this.statRuleItem = this.state.departureConditions[this.currentIndex];
      isSplice = true;
    }else if(this.state.isEditModal){
      this.statRuleItem = this.state.returnConditions[this.currentIndex];
      isSplice = true;
    }
    this.statRuleItem[0].amountReferenceStandard = subsidy.isUseStandard;
    this.statRuleItem[0].amountOperator = subsidy.restriction;
    this.statRuleItem[0].amountOperatorDivisor = subsidy.divisor;
    this.statRuleItem[0].amount = subsidy.amount;
    if(!isSplice){
      this.statRuleItem[0].batchCode = res.data;
      this.statRuleItem[1].batchCode = res.data;
    }
    this.statRuleItem[0].values = `${day ? day :''}${(day && week) ? ',' : ''}${week ? week : ''}`;
    this.statRuleItem[0].showValue = `${day ? messages('setting.key1125'/*工作日*/):''}${(day && week) ? '/' : ''}${week ? messages('setting.key1126'/*周末*/):''}`;
    this.statRuleItem[1].amountReferenceStandard = subsidy.isUseStandard;
    this.statRuleItem[1].amountOperator = subsidy.restriction;
    this.statRuleItem[1].amountOperatorDivisor = subsidy.divisor;
    this.statRuleItem[1].amount = subsidy.amount;
    this.statRuleItem[1].values = `[${startTime}${endTime ? ',':''}${endTime}]`;
    this.statRuleItem[1].showValue = `${startTime}~${endTime}`;
    if(this.currentAddIsDeparture){
      let arr = this.state.departureConditions;
      if(isSplice){
        arr.splice(this.currentIndex,1,this.statRuleItem);
        this.standardAmountChange(this.props.form.getFieldValue('standardAmount'));
      }else{
        arr.push(this.statRuleItem);
      }
      this.setState({departureConditions:arr});
    }else{
      let arr = this.state.returnConditions;
      if(isSplice){
        arr.splice(this.currentIndex,1,this.statRuleItem);
        this.standardAmountChange(this.props.form.getFieldValue('standardAmount'));
      }else{
        arr.push(this.statRuleItem);
      }
      this.setState({returnConditions:arr});
    }
    this.setState({isRequest:false});
    this.resetModalForm();
  };

  //取消弹框
  cancelAddRule = (notRest) =>{
    this.setState({isAddNewRule:false});
    this.resetModalForm();
  };

  //重置modal
  resetModalForm = () =>{
    this.props.form.resetFields(['workDay','workWeek','departureDefault','returnDefault','normalSubsidy','startTime','endTime']);
  };

  //展示弹框新建规则
  addRuleModal = (type) =>{
    this.setState({isEditModal:false,isShowDefaultTip:false,isDeparture:false});
    let newItem = [
      {
        amountReferenceStandard:true,//是否使用标准
        amountOperator:1001, // + - * /
        amountOperatorDivisor:1,//因数
        amount:this.props.form.getFieldValue('standardAmount'),//金额
        messageKey:"HOLIDAY_WEEKEND",
        fieldType:101,
        sequence:0,
        batchCode:"",
        restriction:1006,
        values:"",//周末、工作日 1003  1001
      },
      {
        amountReferenceStandard:true,
        amountOperator:1001,
        amountOperatorDivisor:1,
        amount:this.props.form.getFieldValue('standardAmount'),
        messageKey:"DEPARTURE_RETURN_TIME",
        fieldType:101,
        sequence:1,
        batchCode:"",
        restriction:1008,
        values:"",
      }
    ];
    switch (type){
      case 'departure':
        this.currentAddIsDeparture = true;
        break;
      case 'return':
        this.currentAddIsDeparture = false;
        break;
    }
    this.statRuleItem = newItem;
    this.setState({isAddNewRule:true});
  };

  //选择币种
  selectCode = (value) =>{
    this.setState({currentCodeShow:value});
    this.props.form.getFieldsValue().hasOwnProperty('standardAmount') &&
    this.props.form.setFieldsValue({
      'standardAmount': currencyPrecisionCal(value, this.props.form.getFieldValue('standardAmount'))
    });
    this.standardAmountChange(this.props.form.getFieldValue('standardAmount'));
  };

  //删除当前添加的某一规则
  deleteNewRule = (type,index) =>{
    const {returnConditions,departureConditions} = this.state;
    switch (type){
      case 'departure':
        departureConditions.splice(index,1);
        this.setState({departureConditions});
        break;
      case 'return':
        returnConditions.splice(index,1);
        this.setState({returnConditions});
        break;
    }
  };

  //格式化modal所需要的数据
  formatModalItem = (index, type) =>{
    let item = {
      day:true,
      week:true,
      start:moment('00:00','HH:mm'),
      end:moment('23:59','HH:mm'),
      sub:''
    };
    let isDefault = false;
    switch (type){
      case 'departure':item = this.state.departureConditions[index];break;
      case 'return':item = this.state.returnConditions[index];break;
      case 'default_departure':isDefault = true;
        item.sub = {
          isUseStandard:this.departureIsUseStandard,//是否引用不标准
          restriction:this.departureOperator,//操作符
          divisor:this.departureOperatorDivisor,//因数
          amount:this.departureAmount,//金额最终值
          needUpdate:true,//重置
        };
        break;
      case 'default_return':isDefault = true;
        item.sub = {
          isUseStandard:this.returnIsUseStandard,//是否引用不标准
          restriction:this.returnOperator,//操作符
          divisor:this.returnOperatorDivisor,//因数
          amount:this.returnAmount,//金额最终值
          needUpdate:true,//重置
        };
        break;
    }
    let returnItem = "";
    if(!isDefault){
      returnItem = {
        day:item[0].values.indexOf('1001') >= 0 ? true : false,
        week:item[0].values.indexOf('1003') >= 0 ? true : false,
        start:moment(item[1].values.split(',')[0],'HH:mm'),
        end:moment(item[1].values.split(',')[1],'HH:mm'),
        sub:{
          isUseStandard:item[0].amountReferenceStandard,//是否引用不标准
          restriction:item[0].amountOperator,//操作符
          divisor:item[0].amountOperatorDivisor,//因数
          amount:item[0].amount,//金额最终值
          needUpdate:true,//重置
        }
      }
    }
    return isDefault ? item : returnItem;
  };

  //编辑 出差当天、返回当天的默认规则
  editRuleModal = (type, index) =>{
    this.setState({isEditModal:true});
    let item = "";
    switch (type){
      case 'departure':
        this.currentAddIsDeparture = true;
        this.currentIndex = index;
        item = this.formatModalItem(index,'departure');
        this.setState({isShowDefaultTip:false,isDeparture:false,editRuleItem:item},()=>{
          this.props.form.resetFields('normalSubsidy');
        });
        break;
      case 'return':
        this.currentAddIsDeparture = false;
        this.currentIndex = index;
        item = this.formatModalItem(index,'return');
        this.setState({isShowDefaultTip:false,isDeparture:false,editRuleItem:item});
        break;
      case 'default_departure':
        this.currentAddIsDeparture = false;
        item = this.formatModalItem(index,'default_departure');
        this.setState({isShowDefaultTip:true,isDeparture:true,editRuleItem:item});
        break;
      case 'default_return':
        this.currentAddIsDeparture = false;
        item = this.formatModalItem(index,'default_return');
        this.setState({isShowDefaultTip:true,isDeparture:false,editRuleItem:item});
        break;
    }
    this.setState({isAddNewRule:true});
  };

  //标准金额变动
  standardAmountChange = (value) =>{
    const { departure,backReturn, departureConditions, returnConditions} = this.state;
    let lessThan = false;
    if(this.departureIsUseStandard){
      departure.amount = ruleUtil.calculateWeek(ruleUtil.restrictionChange(this.departureOperator),value,this.departureOperatorDivisor);
      this.departureAmount = departure.amount;
      if(this.departureAmount < 0){
        lessThan = true;
      }
    }
    if(this.returnIsUseStandard){
      backReturn.amount = ruleUtil.calculateWeek(ruleUtil.restrictionChange(this.returnOperator),value,this.returnOperatorDivisor);
      this.returnAmount = backReturn.amount;
      if(this.returnAmount < 0){
        lessThan = true;
      }
    }
    departureConditions.map(item =>{
      if(item[0].amountReferenceStandard){
        item[0].amount = ruleUtil.calculateWeek(ruleUtil.restrictionChange(item[0].amountOperator),value,item[0].amountOperatorDivisor);
        item[1].amount = item[0].amount;
        if(item[0].amount < 0){
          lessThan = true;
        }
      }
    });
    returnConditions.map(item =>{
      if(item[0].amountReferenceStandard){
        item[0].amount = ruleUtil.calculateWeek(ruleUtil.restrictionChange(item[0].amountOperator),value,item[0].amountOperatorDivisor);
        item[1].amount = item[0].amount;
        if(item[0].amount < 0){
          lessThan = true;
        }
      }
    });
    this.amountLessThanZero = lessThan;
    this.setState({departure,backReturn});
  };

  //查看规则名称是否重复
  isRepeatName = (nameCopy) =>{
    let name = nameCopy ? nameCopy : this.props.form.getFieldValue('name');
    if(name){
      let typeOID = this.props.params.isCopyRule ? this.props.params.copyTarget.expenseTypeOID : this.props.params.btnItem.expenseTypeOID;
      let travelOID = false;
      if(this.statusIsEdit){
        travelOID = this.props.params.btnItem.id;
      }
      SubsidyRuleService.checkedRuleNameIsRepeat(typeOID, this.props.params.formOID, name, travelOID).then(res =>{
        this.ruleNameRepeat = res.data;
        if(this.ruleNameRepeat){
          message.error(messages('setting.key1117'/*规则名重复*/));
        }
      }).catch(err =>{
        message.error(err.response.data.message);
      })
    }
  };

  //币种过滤器
  searchCode = (input, option) => {
    return option.props.children.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0;
  }

  // 关闭侧滑
  closeSlide = (isDelay) => {
    if(isDelay === true){
      setTimeout(()=>{
        this.setState({isOk:false,isOkAndCopy:false});
        this.props.close();
      },1000)
    }else{
      this.props.close();
    }
  };

  render(){
    const { citys, chooserItem, isRequest, unInstallWeek, editRuleDetailItem, isOkAndCopy, isOk, fieldValueData,
      departureConditions, returnConditions, isDeparture, currentCode, formInfo, isAddNewRule,departure, backReturn,
      isEditModal, isShowDefaultTip, editRuleItem, itineraryValueData } = this.state;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const {readonly} = this.props.params;
    const layout = {
      labelCol: {span: 6},
      wrapperCol: {span: 18}
    }
    const modalLayout = {
      paddingTop: 5,
      textAlign: 'right',
      paddingRight: 7,
      color: '#404040'
    }
    return (
      <div className="new-subsidy-rule">
        <div className="base-slide-title">
          <sapn className="span-title">{messages('setting.key1127'/*基础条件设置*/)}</sapn>
        </div>

        <Spin spinning={isOk || isOkAndCopy}>
          <div>
            <Form>
              <FormItem {...layout} label={messages('setting.key1086'/*启用*/)}>
                {getFieldDecorator('enabled',{
                  valuePropName: 'checked',
                  initialValue:editRuleDetailItem.hasOwnProperty('enabled') ? editRuleDetailItem.enabled : true
                })(
                  <Switch disabled={readonly}></Switch>
                )}
              </FormItem>
              <FormItem {...layout} label={messages('setting.key1091'/*规则名称*/)}>
                {getFieldDecorator('name',{
                  rules:[{
                    required:true,
                    message:messages('setting.key1471',{arg1:messages('setting.key1091'/*规则名称*/)}/*{arg1}不能为空*/)
                  }],
                  initialValue:editRuleDetailItem.name ? editRuleDetailItem.name : ''
                })(
                  <Input disabled={readonly} maxLength="100" onBlur={()=>this.isRepeatName()} style={{width:335}} placeholder={messages('expense-reimbursement-control.key2')/*最多输入100个字符*/}/>
                )}
              </FormItem>
              {
                formInfo.travelFieldDimension && formInfo.travelFieldDimension.indexOf('TRAVEL_HOURS') >= 0 && <Row>
                  <Col span={6} className="form-label">{messages('setting.key1128'/*出差时长(小时)*/)}:</Col>
                  <Col span={18} style={{display:'flex'}}>
                    <FormItem>
                      {getFieldDecorator('hour2',{
                        initialValue:ruleUtil.parseDetailRule(editRuleDetailItem,'TRAVEL_HOURS',1,'')
                      })(
                        <InputNumber disabled={readonly} step={1} precision={2} min={0} placeholder={messages('setting.key1129'/*不限*/)}/>
                      )}
                    </FormItem>
                    <FormItem className="form-item-content">
                      {getFieldDecorator('hour3',{
                        initialValue:ruleUtil.parseDetailRule(editRuleDetailItem,'TRAVEL_HOURS',0,1003)
                      })(
                        <Select disabled={readonly} getPopupContainer={triggerNode => triggerNode.parentNode}>
                          <Option value={1003}>{'≤'}</Option>
                          <Option value={1002}>{'<'}</Option>
                        </Select>
                      )}
                    </FormItem>
                    <span style={{marginTop:9}}>&nbsp;&nbsp;{messages('setting.key1130'/*时长*/)}&nbsp;&nbsp;</span>
                    <FormItem className="form-item-content">
                      {getFieldDecorator('hour4',{
                        initialValue:ruleUtil.parseDetailRule(editRuleDetailItem,'TRAVEL_HOURS',3,1005)
                      })(
                        <Select disabled={readonly} getPopupContainer={triggerNode => triggerNode.parentNode}>
                          <Option value={1005}>{'≤'}</Option>
                          <Option value={1004}>{'<'}</Option>
                        </Select>
                      )}
                    </FormItem>
                    <FormItem style={{marginLeft:4}}>
                      {getFieldDecorator('hour5',{
                        initialValue:ruleUtil.parseDetailRule(editRuleDetailItem,'TRAVEL_HOURS',2,'')
                      })(
                        <InputNumber disabled={readonly} step={1} precision={2} min={0}  placeholder={messages('setting.key1129'/*不限*/)}/>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              }
              {
                formInfo.travelFieldDimension && formInfo.travelFieldDimension.indexOf('TRAVEL_DAYS') >= 0  && <Row>
                  <Col span={6} className="form-label">{messages('setting.key1131'/*出差天数(天)*/)}:</Col>
                  <Col span={18} style={{display:'flex',}}>
                    <FormItem>
                      {getFieldDecorator('day2',{
                        initialValue:ruleUtil.parseDetailRule(editRuleDetailItem,'TRAVEL_DAYS',1,'')
                      })(
                        <InputNumber disabled={readonly} step={1} precision={2} min={0}  placeholder={messages('setting.key1129'/*不限*/)}/>
                      )}
                    </FormItem>
                    <FormItem className="form-item-content">
                      {getFieldDecorator('day3',{
                        initialValue:ruleUtil.parseDetailRule(editRuleDetailItem,'TRAVEL_DAYS',0,1003)
                      })(
                        <Select disabled={readonly} getPopupContainer={triggerNode => triggerNode.parentNode}>
                          <Option value={1003}>{'≤'}</Option>
                          <Option value={1002}>{'<'}</Option>
                        </Select>
                      )}
                    </FormItem>
                    <span style={{marginTop:9}}>&nbsp;&nbsp;{messages('setting.key1132'/*天数*/)}&nbsp;&nbsp;</span>
                    <FormItem className="form-item-content">
                      {getFieldDecorator('day4',{
                        initialValue:ruleUtil.parseDetailRule(editRuleDetailItem,'TRAVEL_DAYS',3,1005)
                      })(
                        <Select disabled={readonly} getPopupContainer={triggerNode => triggerNode.parentNode}>
                          <Option value={1005}>{'≤'}</Option>
                          <Option value={1004}>{'<'}</Option>
                        </Select>
                      )}
                    </FormItem>
                    <FormItem style={{marginLeft:4}}>
                      {getFieldDecorator('day5',{
                        initialValue:ruleUtil.parseDetailRule(editRuleDetailItem,'TRAVEL_DAYS',2,'')
                      })(
                        <InputNumber disabled={readonly} step={1} precision={2} min={0}  placeholder={messages('setting.key1129'/*不限*/)}/>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              }

              <div>
                <Row>
                  <Col span={6} className="form-label">{messages('setting.key1092'/*适用人员*/)}:</Col>
                  <Col span={18} style={{display:'flex'}}>
                    <FormItem>
                      {getFieldDecorator('ori_user_restriction',{
                        initialValue: ruleUtil.parseDetailRule(editRuleDetailItem, 'USER_GROUPS' , -1, [], 0, readonly)
                      })(
                        <Select
                          disabled={readonly}
                          style={{width:90}}
                          getPopupContainer={triggerNode => triggerNode.parentNode}>
                          <Option value={1006}>{messages('setting.key1133'/*包含*/)}</Option>
                          <Option value={1007}>{messages('setting.key1134'/*不包含*/)}</Option>
                        </Select>
                      )}
                    </FormItem>
                    <FormItem style={{width: '100%', marginLeft: 12}}>
                      {getFieldDecorator('ori_user',{
                        initialValue:ruleUtil.parseDetailRule(editRuleDetailItem, 'USER_GROUPS', -1, [], 1, readonly)
                      })(
                        <Chooser selectorItem={chooserItem}
                                 valueKey="userGroupOID"
                                 labelKey="name"
                                 disabled={readonly}
                                 placeholder={
                                   getFieldValue('ori_user_restriction') === 1006 ?
                                     messages('setting.key774'/*通用*/) : messages('common.please.select'/*请选择*/)
                                 }
                                 newline={true}/>
                      )}
                    </FormItem>
                  </Col>
                </Row>
                {readonly &&
                <Row className="city-user-toast">
                  <Col offset={6}>
                    <Icon style={{color: '#faad14', paddingRight: '3px'}} type="info-circle"/>{messages('setting.key1652')/*帐套级人员组*/}
                  </Col>
                </Row>}
              </div>
              {formInfo.defaultDimensions && formInfo.defaultDimensions.indexOf('ALLOWANCE_CITY') >= 0 && (
                <Row>
                  <Col span={6} className="form-label">{messages('setting.key1093'/*差补城市*/)}:</Col>
                  <Col span={18} style={{display:'flex'}}>
                    <FormItem>
                      {getFieldDecorator('ori_city_restriction',{
                        initialValue: ruleUtil.parseDetailRule(editRuleDetailItem, 'ALLOWANCE_CITY', -1, [], 0, readonly)
                      })(
                        <Select
                          disabled={readonly}
                          style={{width:90}}
                          getPopupContainer={triggerNode => triggerNode.parentNode}>
                          <Option value={1006}>{messages('setting.key1133'/*包含*/)}</Option>
                          <Option value={1007}>{messages('setting.key1134'/*不包含*/)}</Option>
                        </Select>
                      )}
                    </FormItem>
                    <FormItem style={{width: '100%', marginLeft: 12}}>
                      {getFieldDecorator('ori_city',{
                        initialValue: ruleUtil.parseDetailRule(editRuleDetailItem, 'ALLOWANCE_CITY', -1, [], 1, readonly)
                      })(
                        <Select
                          disabled={readonly}
                          optionFilterProp="children"
                          getPopupContainer={triggerNode => triggerNode.parentNode}
                          placeholder={
                            getFieldValue('ori_city_restriction') === 1006 ?
                              messages('setting.key774'/*通用*/) : messages('common.please.select'/*请选择*/)
                          }
                          mode="multiple">
                          {
                            citys.map(item => {
                              return <Option key={item.levelOID}>{item.levelName}</Option>
                            })
                          }
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              )}
              {readonly && formInfo.defaultDimensions && formInfo.defaultDimensions.indexOf('ALLOWANCE_CITY') >= 0 && <Row className="city-user-toast">
                <Col offset={6}>
                  <Icon style={{color: '#faad14', paddingRight: '3px'}} type="info-circle"/>{messages('setting.key1653')/*帐套级城市组*/}
                </Col>
              </Row>}
              {
                formInfo.formFields && formInfo.formFields.map((item,fieldIndex)=>{
                  return (
                    <Row key={item.id}>
                      <Col span={6} className="form-label">{item.fieldName}:</Col>
                      <Col span={18} style={{display:'flex'}}>
                        <FormItem>
                          {getFieldDecorator('range'+fieldIndex,{
                            initialValue:ruleUtil.parseDetailRule(editRuleDetailItem,'CUST_LIST',this.getCustomEnumerationOID(fieldIndex),1006,0)
                          })(
                            <Select
                              disabled={readonly}
                              style={{width:90}}
                              getPopupContainer={triggerNode => triggerNode.parentNode}>
                              <Option value={1006}>{messages('setting.key1133'/*包含*/)}</Option>
                              <Option value={1007}>{messages('setting.key1134'/*不包含*/)}</Option>
                              <Option value={1009}>{messages('setting.key1135'/*为空*/)}</Option>
                              <Option value={1010}>{messages('setting.key1136'/*不为空*/)}</Option>
                            </Select>
                          )}
                        </FormItem>
                        {
                          this.props.form.getFieldValue('range'+fieldIndex) < 1008 &&
                          <FormItem style={{width:348,marginTop:-4}}>
                            {getFieldDecorator('field'+fieldIndex,{
                              initialValue:ruleUtil.parseDetailRule(editRuleDetailItem,'CUST_LIST',this.getCustomEnumerationOID(fieldIndex),[],1),
                              rules:[{
                                required:true,
                                message:messages('setting.key1471',{arg1:""}/*{arg1}不能为空*/)
                              }]
                            })(
                              <Select style={{marginTop:4}}
                                      disabled={readonly}
                                      optionFilterProp="children"
                                      getPopupContainer={triggerNode => triggerNode.parentNode}
                                      placeholder={messages('setting.key1137'/*请选择*/)}
                                      mode="multiple">
                                {fieldValueData[fieldIndex] && fieldValueData[fieldIndex].map(item=>{
                                  return <Option key={item.value}>{item.messageKey}</Option>
                                })}
                              </Select>
                            )}
                          </FormItem>
                        }
                      </Col>
                    </Row>
                  )
                })
              }
              {formInfo.itineraryFieldList && formInfo.itineraryFieldList.map(field => {
                return (
                  <Row key={field.customEnumerationOID}>
                    <Col span={6} className="form-label">{field.name}:</Col>
                    <Col span={18} style={{display:'flex'}}>
                      <FormItem>
                        {getFieldDecorator('range' + field.customEnumerationOID, {
                          initialValue:ruleUtil.parseDetailRule(editRuleDetailItem, 'ITINERARY_CUST_LIST', field.customEnumerationOID, 1006, 0)
                        })(
                          <Select
                            disabled={readonly}
                            style={{width:90}}
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                          >
                            <Option value={1006}>{messages('setting.key1133'/*包含*/)}</Option>
                            <Option value={1007}>{messages('setting.key1134'/*不包含*/)}</Option>
                            <Option value={1009}>{messages('setting.key1135'/*为空*/)}</Option>
                            <Option value={1010}>{messages('setting.key1136'/*不为空*/)}</Option>
                          </Select>
                        )}
                      </FormItem>
                      {
                        this.props.form.getFieldValue('range' + field.customEnumerationOID) < 1008 &&
                        <FormItem style={{width: 348, marginLeft: 12}}>
                          {getFieldDecorator('field' + field.customEnumerationOID, {
                            initialValue:ruleUtil.parseDetailRule(editRuleDetailItem, 'ITINERARY_CUST_LIST', field.customEnumerationOID, [], 1),
                            rules:[{
                              required:true,
                              message:messages('setting.key1471',{arg1:""}/*{arg1}不能为空*/)
                            }]
                          })(
                            <Select
                              disabled={readonly}
                              optionFilterProp="children"
                              getPopupContainer={triggerNode => triggerNode.parentNode}
                              placeholder={messages('setting.key1137'/*请选择*/)}
                              mode="multiple"
                            >
                              {itineraryValueData[field.customEnumerationOID] && itineraryValueData[field.customEnumerationOID].map(item => {
                                return <Option key={item.value}>{item.messageKey}</Option>
                              })}
                            </Select>
                          )}
                        </FormItem>
                      }
                    </Col>
                  </Row>
                )
              })}
            </Form>
          </div>
        </Spin>

        <div className="base-slide-title">
          <span className="span-title">{messages('setting.key1138'/*金额标准(天)设置*/)}</span>
          <span>&nbsp;{messages('setting.key1139'/*金额取值优先级: 出差当天 > 返回当天 > 法定节假日 > 周末／标准差补*/)}</span>
        </div>

        <Spin spinning={isRequest}>
          <div className="slide-modal-add-edit">
            <Form>
              <Row>
                <Col span={6} className="form-label">{messages('setting.key1140'/*标准差补*/)}:</Col>
                <Col span={18} style={{display:'flex'}}>
                  <FormItem>
                    {getFieldDecorator('currencyCode',{
                      rules:[{
                        required:true,
                        message:messages('setting.key1471',{arg1:messages('setting.key1140'/*标准差补*/)}/*{arg1}不能为空*/)
                      }],
                      initialValue:editRuleDetailItem.currencyCode ? editRuleDetailItem.currencyCode : (currentCode.rows ? currentCode.rows[0].currencyCode : '')
                    })(
                      <Select
                        disabled={readonly}
                        onSelect={this.selectCode}
                        style={{width:180}}
                        optionFilterProp="children"
                        showSearch={true}
                        notFoundContent={messages('setting.key1141'/*无匹配结果*/)}
                        filterOption={(input,option)=>this.searchCode(input,option)}
                        getPopupContainer={triggerNode => triggerNode.parentNode}>
                        {currentCode.rows && currentCode.rows.map(item=>{
                          return <Option key={item.currencyCode}>{`${item.currencyCode}${this.props.language.code === 'zh_cn' ? ' '+item.currencyName : ''}`}</Option>
                        })}
                      </Select>
                    )}
                  </FormItem>
                  <FormItem className="form-item-content">
                    {getFieldDecorator('standardAmount',{
                      rules:[{
                        required:true,
                        message:messages('setting.key1471',{arg1:messages('setting.key1140'/*标准差补*/)}/*{arg1}不能为空*/)
                      }],
                      initialValue:editRuleDetailItem.standardAmount ? editRuleDetailItem.standardAmount : 0
                    })(<InputNumber disabled={readonly} onChange={this.standardAmountChange} step={1} precision={queryCurrencyPrecision(this.props.form.getFieldValue('currencyCode'))} min={0}/>)}
                  </FormItem>
                </Col>
              </Row>
              {
                formInfo.specialDimension && formInfo.specialDimension.indexOf('HOLIDAY_WEEKEND') >= 0 && !unInstallWeek &&
                <FormItem style={{marginBottom:0}}>
                  {getFieldDecorator('weekend',{
                    initialValue:{
                      needUpdate:true,
                      isUseStandard:editRuleDetailItem.hasOwnProperty('weekendReferenceStandard') ? editRuleDetailItem.weekendReferenceStandard : true,//是否引用不标准
                      restriction:editRuleDetailItem.hasOwnProperty('weekendOperator') ? editRuleDetailItem.weekendOperator : 1001,//操作符
                      divisor:editRuleDetailItem.hasOwnProperty('weekendOperatorDivisor') ? editRuleDetailItem.weekendOperatorDivisor : 1,//因数
                      amount:editRuleDetailItem.hasOwnProperty('weekendAmount') ? editRuleDetailItem.weekendAmount : 0,
                    }
                  })(
                    <CalculateForm
                      disabled={readonly}
                      labelName={messages('setting.key1142'/*周末差补*/)}
                      standardAmount={parseFloat(this.props.form.getFieldValue('standardAmount'))}
                      currentCode={this.props.form.getFieldValue('currencyCode')}/>
                  )
                  }
                </FormItem>
              }
              {
                formInfo.specialDimension && formInfo.specialDimension.indexOf('DEPARTURE_DAY') >= 0 && <Row style={{marginBottom:24}}>
                  <Col span={6} className="form-label">{messages('setting.key1143'/*出差当天差补*/)}:</Col>
                  <Col span={18}>
                    {!readonly&&<Button onClick={()=>this.addRuleModal('departure')}>{messages('setting.key1144'/*+新建规则*/)}</Button>}
                    <Row className="table-title">
                      <Col span={16}>{messages('setting.key1145'/*出差时间*/)}</Col>
                      <Col span={5}>{messages('setting.key1146'/*差补金额*/)}</Col>
                      {!readonly&&<Col span={3}>{messages('setting.key1147'/*操作*/)}</Col>}
                    </Row>
                    <Row className="table-content" onClick={()=>this.editRuleModal('default_departure')}>
                      <Col span={16}>{messages('setting.key1148'/*当未能匹配其他规则时，系统将引用该金额*/)}</Col>
                      <Col span={5} style={{color:departure.amount < 0 ? 'red' : ''}}>{currencyPrecisionCal(this.props.form.getFieldValue('currencyCode'), departure.amount)}</Col>
                      {!readonly&&<Col span={3}>{messages('setting.key1149'/*不可删除*/)}</Col>}
                    </Row>
                    {departureConditions.map((item, index)=>{
                      return (
                        <Row key={item[0].batchCode} className="table-content" onClick={()=>this.editRuleModal('departure',index)}>
                          <Col span={16}>{item[0].showValue}&nbsp;{item[1].showValue}</Col>
                          <Col span={5} style={{color:item[0].amount < 0 ? 'red' : ''}}>{currencyPrecisionCal(this.props.form.getFieldValue('currencyCode'), item[0].amount)}</Col>
                          {!readonly&&<Col span={3}>
                            <Popconfirm title={messages('setting.key1150'/*你确定删除这行内容吗?*/)}
                                        onConfirm={()=>this.deleteNewRule('departure',index)}
                                        okText={messages('setting.key1100'/*确定*/)}
                                        cancelText={messages('setting.key1080'/*取消*/)}>
                              <a onClick={(e) => {e.stopPropagation()}}>{messages('setting.key1101'/*删除*/)}</a>
                            </Popconfirm>
                          </Col>}
                        </Row>
                      )
                    })}
                  </Col>
                </Row>
              }
              {
                formInfo.specialDimension && formInfo.specialDimension.indexOf('RETURN_DAY') >= 0 && <Row style={{marginBottom:24}}>
                  <Col span={6} className="form-label">{messages('setting.key1151'/*返回当天差补*/)}:</Col>
                  <Col span={18}>
                    {!readonly&&<Button onClick={()=>this.addRuleModal('return')}>{messages('setting.key1144'/*+新建规则*/)}</Button>}
                    <Row className="table-title">
                      <Col span={16}>{messages('setting.key1145'/*出差时间*/)}</Col>
                      <Col span={5}>{messages('setting.key1146'/*差补金额*/)}</Col>
                      {!readonly&&<Col span={3}>{messages('setting.key1147'/*操作*/)}</Col>}
                    </Row>
                    <Row className="table-content" onClick={()=>this.editRuleModal('default_return')}>
                      <Col span={16}>{messages('setting.key1148'/*当未能匹配其他规则时，系统将引用该金额*/)}</Col>
                      <Col span={5} style={{color:backReturn.amount < 0 ? 'red' : ''}}>{currencyPrecisionCal(this.props.form.getFieldValue('currencyCode'), backReturn.amount)}</Col>
                      {!readonly&&<Col span={3}>{messages('setting.key1149'/*不可删除*/)}</Col>}
                    </Row>
                    {returnConditions.map((item, index)=>{
                      return (
                        <Row key={item[0].batchCode} className="table-content" onClick={()=>this.editRuleModal('return',index)}>
                          <Col span={16}>{item[0].showValue}&nbsp;{item[1].showValue}</Col>
                          <Col span={5} style={{color:item[0].amount < 0 ? 'red' : ''}}>{currencyPrecisionCal(this.props.form.getFieldValue('currencyCode'), item[0].amount)}</Col>
                          {!readonly&&<Col span={3}>
                            <Popconfirm title={messages('setting.key1150'/*你确定删除这行内容吗?*/)}
                                        onConfirm={()=>this.deleteNewRule('return',index)}
                                        okText={messages('setting.key1100'/*确定*/)}
                                        cancelText={messages('setting.key1080'/*取消*/)}>
                              <a onClick={(e) => {e.stopPropagation()}}>{messages('setting.key1101'/*删除*/)}</a>
                            </Popconfirm>
                          </Col>}
                        </Row>
                      )
                    })}
                  </Col>
                </Row>
              }
            </Form>
          </div>
        </Spin>
        <br className="change-line"/>
        <Affix className="travel-affix" offsetBottom={0}>
          <Button disabled={isOk || isOk || readonly} onClick={()=>this.toSubmitNewRule('commit')} type="primary" loading={isOk}>{messages('setting.key1100'/*确定*/)}</Button>
          <Button disabled={isOkAndCopy || isOk ||readonly} onClick={()=>this.toSubmitNewRule('copy')} style={{marginLeft:12}} loading={isOkAndCopy}>{messages('setting.key1152'/*确认并复制*/)}</Button>
          <Button disabled={isOk || isOkAndCopy} style={{marginLeft:12}} onClick={this.closeSlide}>{messages('setting.key1080'/*取消*/)}</Button>
        </Affix>
        {
          isAddNewRule && <Modal title={isEditModal ? messages('finance-setting.key81')/*'编辑规则'*/ : messages('finance-setting.key84')/*'新建规则'*/}
                                 visible={isAddNewRule}
                                 onOk={this.toSaveSingleRule}
                                 onCancel={()=>this.cancelAddRule(false)}
                                 okText={messages('setting.key1100'/*确定*/)}
                                 cancelText={messages('setting.key1080'/*取消*/)}
                                 width={'50%'}
          >
            {isShowDefaultTip &&
            <Alert message={messages('setting.key1148'/*当未能匹配其他规则时，系统将引用该金额*/)} type="info" showIcon/>
            }
            <Form>
              <Row>
                <Col span={6} style={modalLayout}>{messages('setting.key1145'/*出差时间*/)}:</Col>
                <Col span={18} style={{display:'flex'}}>
                  <FormItem>
                    {getFieldDecorator('workDay',{
                      valuePropName: 'checked',
                      initialValue:isShowDefaultTip ? true : (isEditModal ? editRuleItem.day : false )
                    })(
                      <Checkbox disabled={isShowDefaultTip||readonly}>{messages('setting.key1125'/*工作日*/)}</Checkbox>
                    )}
                  </FormItem>
                  <FormItem>
                    {getFieldDecorator('workWeek',{
                      valuePropName: 'checked',
                      initialValue:isShowDefaultTip ? true : (isEditModal ? editRuleItem.week : false )
                    })(
                      <Checkbox disabled={isShowDefaultTip||readonly}>{messages('setting.key1126'/*周末*/)}</Checkbox>
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={6} style={modalLayout}></Col>
                <Col span={18} style={{display:'flex'}}>
                  <FormItem>
                    {getFieldDecorator('startTime',{
                      initialValue:isShowDefaultTip ? moment('00:00','HH:mm') : (isEditModal ? editRuleItem.start : moment('00:00','HH:mm') )
                    })(
                      <TimePicker format="HH:mm" disabled={isShowDefaultTip||readonly}/>
                    )}
                  </FormItem>
                  <span style={{marginTop:10}}>&nbsp;{messages('setting.key22')/*至*/}&nbsp;</span>
                  <FormItem>
                    {getFieldDecorator('endTime',{
                      initialValue:isShowDefaultTip ? moment('23:59','HH:mm') : (isEditModal ? editRuleItem.end : moment('23:59','HH:mm') )
                    })(
                      <TimePicker format="HH:mm" disabled={isShowDefaultTip||readonly}/>
                    )}
                  </FormItem>
                </Col>
              </Row>
              {
                isShowDefaultTip ? (
                    isDeparture ? <FormItem style={{marginBottom:0}}>
                        {getFieldDecorator('departureDefault',{
                          initialValue:isEditModal ? editRuleItem.sub : {}
                        })(
                          <CalculateForm
                            disabled={readonly}
                            labelName={messages('setting.key1146'/*差补金额*/)}
                            standardAmount={parseFloat(this.props.form.getFieldValue('standardAmount'))}
                            currentCode={this.props.form.getFieldValue('currencyCode')}/>
                        )
                        }
                      </FormItem>:
                      <FormItem style={{marginBottom:0}}>
                        {getFieldDecorator('returnDefault',{
                          initialValue:isEditModal ? editRuleItem.sub : {}
                        })(
                          <CalculateForm
                            disabled={readonly}
                            labelName={messages('setting.key1146'/*差补金额*/)}
                            standardAmount={parseFloat(this.props.form.getFieldValue('standardAmount'))}
                            currentCode={this.props.form.getFieldValue('currencyCode')}/>
                        )
                        }
                      </FormItem>
                  ):<FormItem style={{marginBottom:0}}>
                    {getFieldDecorator('normalSubsidy',{
                      initialValue:isEditModal ? editRuleItem.sub : {}
                    })(
                      <CalculateForm
                        disabled={readonly}
                        labelName={messages('setting.key1146'/*差补金额*/)}
                        standardAmount={parseFloat(this.props.form.getFieldValue('standardAmount'))}
                        currentCode={this.props.form.getFieldValue('currencyCode')}/>
                    )
                    }
                  </FormItem>
              }

            </Form>
          </Modal>
        }
      </div>
    )
  };
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    language: state.main.language,
    profile: state.login.profile,
    tenantMode: state.main.tenantMode
  }
}

const wrappedNewSubsidyRules = Form.create()(NewSubsidyRules);

export default connect(mapStateToProps)(wrappedNewSubsidyRules);


